"""菜单管理视图函数业务逻辑模块"""
import datetime
import traceback

from air_web.data_platform import mysql_con
from air_web.web_flask import get_default_result
from air_web.web_flask.bll.base_bll import BaseBll
from air_web.web_flask.common.constants import (  # , POWERLOAD, POWERLOAD_AREA, POWERLOAD_DAY
    ReturnType,
    Status,
)


class MenuManagementBll(BaseBll):
    """菜单管理视图函数业务逻辑类"""

    def __init__(
        self,
    ):
        """
        如果当前页面用到mysql则init_mysql_dal=True，self.sql_dal就会提供mysql实例，不用到则传False
        如果当前页面用到es则init_es_dal=True，self.es_dal就会提供es实例，不用到则传False
        """
        super().__init__(init_mysql_dal=True, init_es_dal=False)

    def sql_from(self, sql, value=None):
        return [{"sql": sql, "value": value}]

    def add_menu(self, params):
        """
        新增菜单
        :return: dict
        """
        try:
            result = get_default_result()
            title = params.get("title")
            jump = params.get("jump")
            priority = params.get("priority")
            is_publish = params.get("is_publish")
            report_url = params.get("report_url")
            # 判断传入title在mysql表中是否存在
            sql_1 = (
                f"""select id from safe_system_menu where title = '{title}' """
            )
            res_1 = mysql_con.get(sql_1)
            if res_1:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "添加的菜单名称已存在，请修改信息后再进行操作！"
            if " " in title:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "输入的菜单名称不能含有空格！"
            if len(title) > 50:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "输入的菜单名称过长，菜单名称输入范围是1-50！"
            if is_publish not in [0, 1]:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "是否启用参数输入有误，请检查传入参数！"
            if result["status"] == 0:
                # 组装写入mysql的数据
                release_date = datetime.date.today()
                # 组装sql
                sql_insert = """INSERT IGNORE INTO safe_system_menu (title,jump,priority,report_url,is_publish,release_date) VALUES (%s,%s,%s,%s,%s,%s);"""
                value = [
                    title,
                    jump,
                    priority,
                    report_url,
                    is_publish,
                    release_date,
                ]
                sql_list = self.sql_from(sql_insert, value)
                mysql_con.execute(sql_list)
            return result
        except:
            self.logger.error(traceback.format_exc())
            return ReturnType.ERROR

    def get_menu(self, params):
        """
        查询菜单信息
        :return: dict
        """
        try:
            result = get_default_result()
            is_publish = params.get("is_publish")
            page_num = (
                int(params.get("pageNum")) if params.get("pageNum") else 1
            )
            page_size = (
                int(params.get("pageSize")) if params.get("pageSize") else 10
            )
            sql_get = """select id,title,jump,priority,report_url,is_publish,release_date from safe_system_menu where id > 0"""
            if is_publish:
                sql_get += f" and is_publish = {is_publish}"
            res = mysql_con.get(sql_get)
            result["data"]["pageNum"] = page_num
            result["data"]["pageSize"] = page_size
            if res:
                result["data"]["total"] = len(res)
                result["data"]["result"] = res[
                    (page_num - 1) * page_size : page_num * page_size
                ]
            return result
        except:
            self.logger.error(traceback.format_exc())
            return ReturnType.ERROR

    def delete_menu(self, params):
        """
        删除菜单信息
        :return: dict
        """
        try:
            result = get_default_result()
            id_list = params.get("id_list")
            all_alist = []
            sql_1 = f"""select id from safe_system_menu"""
            res_1 = mysql_con.get(sql_1)
            for i in res_1:
                all_alist.append(i.get("id"))
            for j in id_list:
                if j not in all_alist:
                    result["status"] = Status.SERVER_ERROR
                    result["msg"] = "菜单信息不存在，请检查传入参数！"
            if result["status"] == 0:
                # 删除菜单
                # 组装sql
                for id_ in id_list:
                    sql_delete = (
                        """DELETE FROM safe_system_menu WHERE id = %s;"""
                    )
                    value = [id_]
                    sql_list = self.sql_from(sql_delete, value)
                    mysql_con.execute(sql_list)
            return result
        except:
            self.logger.error(traceback.format_exc())
            return ReturnType.ERROR

    def update_menu(self, params):
        """
        修改菜单信息
        :return: dict
        """
        try:
            result = get_default_result()
            id = params.get("id")
            title = params.get("title")
            priority = params.get("priority")
            jump = params.get("jump")
            report_url = params.get("report_url")
            is_publish = params.get("is_publish")
            # 通过id查询菜单是否存在
            sql_1 = f"""select id from safe_system_menu where id = '{id}' """
            res_1 = mysql_con.get(sql_1)
            if not res_1:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "菜单信息不存在，请检查传入参数！"
            if " " in title:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "输入的菜单名称不能含有空格！"
            if len(title) > 50:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "输入的菜单名称过长，菜单名称输入范围是1-50！"
            if is_publish not in [0, 1]:
                result["status"] = Status.SERVER_ERROR
                result["msg"] = "是否启用参数输入有误，请检查传入参数！"
            # 组装update的sql语句
            if result["status"] == 0:
                # 组装写入mysql的数据
                # 组装sql
                sql_update = """UPDATE safe_system_menu SET title=%s,jump=%s,priority=%s,report_url=%s,is_publish=%s where id=%s;"""
                value = [title, jump, priority, report_url, is_publish, id]
                sql_list = self.sql_from(sql_update, value)
                mysql_con.execute(sql_list)
            return result
        except:
            self.logger.error(traceback.format_exc())
            return ReturnType.ERROR
